package com.foxit.pdf2html5.web.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class HashUtil {

	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String getMd5Hash(String fileName) throws Exception {
		return getHash(fileName, "MD5");
	}

	public static String getMd5Hash(byte[] byteArray) throws Exception {
		return getHash(byteArray, "MD5");
	}

	public static String getSHA1Hash(byte[] byteArray) throws Exception {
		return getHash(byteArray, "SHA1");
	}

	public static String getMd5Sha1Hash(String fileName) throws Exception {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(HashUtil.getMd5Hash(fileName));
		stringBuilder.append("-");
		stringBuilder.append(HashUtil.getSHA1Hash(fileName));
		return stringBuilder.toString();
	}

	public static String getMd5Sha1Hash(byte[] byteArray) throws Exception {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(HashUtil.getMd5Hash(byteArray));
		stringBuilder.append("-");
		stringBuilder.append(HashUtil.getSHA1Hash(byteArray));
		return stringBuilder.toString();
	}

	public static String getMd5Hash(InputStream inputStream) throws Exception {
		return getHash(inputStream, "MD5");
	}

	public static String getSHA1Hash(String fileName) throws Exception {
		return getHash(fileName, "SHA1");
	}

	private static String getHash(String fileName, String hashType) throws Exception {
		InputStream fis;
		fis = new FileInputStream(fileName);
		return getHash(fis, hashType);
	}

	private static String getHash(InputStream inputStream, String hashType) throws Exception {
		byte[] buffer = new byte[8 * 1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead = 0;
		while ((numRead = inputStream.read(buffer)) > 0) {
			md5.update(buffer, 0, numRead);
		}
		inputStream.close();
		return toHexString(md5.digest());
	}

	private static String getHash(byte[] byteArray, String hashType) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		return toHexString(md5.digest(byteArray));
	}

	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}
